<%@page import="java.util.TimeZone"%>
<%@page import="java.util.LinkedHashMap"%>
<%@page import="java.util.Calendar"%>
<%@page import="java.util.Map"%>
<%@page import="javax.jdo.Extent"%>
<%@page import="itpenguin.review.entities.Item"%>
<%@page import="javax.jdo.Query"%>
<%@page import="itpenguin.common.PMFactory"%>
<%@page import="javax.jdo.PersistenceManager"%>
<%@page import="java.util.List"%>
<%@ page pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<fmt:setLocale value="ja-JP" />
<%
	// new list
	PersistenceManager pm = PMFactory.getInstance().getPersistenceManager();
	Query query = pm.newQuery("select from itpenguin.review.entities.Item order by reviewDate desc range 0, 5"); 
	List<Item> reviewList = (List<Item>) query.execute();
	pageContext.setAttribute("reviewList", pm.detachCopyAll(reviewList));
	query.closeAll();
	
	// ranking list
	query = pm.newQuery("select from itpenguin.review.entities.Item "
			+ "where reviewYear == yearParam "
			+ "parameters Integer yearParam "
			+ "order by score desc range 0, 3"); 
	reviewList = (List<Item>)query.execute((short)0);
	pageContext.setAttribute("rankingList", pm.detachCopyAll(reviewList));
	query.closeAll();
	
	// rating
	query = pm.newQuery("select count(this) from itpenguin.review.entities.Item "
			+ "where numberOfStars == numberOfStarsParam "
			+ "parameters Integer numberOfStarsParam "); 
	long[] countByRate = new long[11];
	countByRate[0] = (Long)query.execute((short)10);
	countByRate[1] = (Long)query.execute((short)9);
	countByRate[2] = (Long)query.execute((short)8);
	countByRate[3] = (Long)query.execute((short)7);
	countByRate[4] = (Long)query.execute((short)6);
	countByRate[5] = (Long)query.execute((short)5);
	countByRate[6] = (Long)query.execute((short)4);
	countByRate[7] = (Long)query.execute((short)3);
	countByRate[8] = (Long)query.execute((short)2);
	countByRate[9] = (Long)query.execute((short)1);
	countByRate[10] = (Long)query.execute((short)0);
	pageContext.setAttribute("countByRate", countByRate);
	query.closeAll();
	
	// archives
	Map<Short, Map<Short, Short>> arcCounter = new LinkedHashMap<Short, Map<Short, Short>>();
	query = pm.newQuery("select from itpenguin.review.entities.Item order by reviewDate desc");
	reviewList = (List<Item>) query.execute();
	Map<Short, Short> countByMonth = null;
	short counter = 0;
	Calendar cal = Calendar.getInstance();
	cal.setTimeZone(TimeZone.getTimeZone("JST"));
	short previousYear = -1;
	short previousMonth = -1;
	short yearCounter = 0;
	Map<Short, Short> countByYear = new LinkedHashMap<Short, Short>();
	for (Item item : reviewList) {
		cal.setTime(item.getReviewDate());
		
		if (previousMonth != cal.get(Calendar.MONTH)
				|| previousYear != cal.get(Calendar.YEAR)) {
			if (previousMonth != -1) {
				countByMonth.put((short)(previousMonth + 1), counter);
				counter = 0;
			}
			previousMonth = (short)cal.get(Calendar.MONTH);
		}
		
		if (previousYear != cal.get(Calendar.YEAR)) {
			if (previousYear != -1) {
				countByYear.put(previousYear, yearCounter);
				yearCounter = 0;
			}
			
			previousYear = (short)cal.get(Calendar.YEAR);
			countByMonth = new LinkedHashMap<Short, Short>();
			arcCounter.put(previousYear, countByMonth);
		}
		counter++;
		yearCounter++;
	}
	countByMonth.put((short)(previousMonth + 1), counter);
	countByYear.put(previousYear, yearCounter);
	
	query.closeAll();
	pm.close();
	pageContext.setAttribute("arcCounter", arcCounter);
	pageContext.setAttribute("countByYear", countByYear);
%>
<c:if test="${!isMobile}">
	<nav>
		<h1>What's new</h1>
		<ul style="padding-left: 32px;">
			<c:forEach var="review" items="${reviewList}">
				<li class="${review.productGroup}" style="position:relative;"><span class="icon"></span>
				<fmt:formatDate value="${review.reviewDate}" pattern="yyyy/MM/dd" timeZone="JST"/> 
				<span class="star"><span class="star${review.numberOfStars}"></span></span><br/>
				<a href="/review/${review.itemId}">${review.reviewTitle}</a></li>
			</c:forEach>
		<li style="text-align: right;"><a href="/all/1">more &gt;&gt;</a></li>
		</ul>
	</nav>
	<nav>
		<h1>Ranking (in the last year)</h1>
		直近１年間（発売日ではなく、筆者がレビューした日）のランキングです。
		<ul style="padding-left: 30px;">
			<c:forEach varStatus="status" var="review" items="${rankingList}">
				<li class="${review.productGroup}" style="position: relative;">
				<fmt:formatDate value="${review.reviewDate}" pattern="yyyy/MM/dd" timeZone="JST"/> 
				<span class="icon">${status.index + 1}</span>
				${review.score}点<br/>
				<a href="/review/${review.itemId}">${review.reviewTitle}</a>
				</li>
			</c:forEach>
		<li style="text-align: right;"><a href="/rank/0/1">more &gt;&gt;</a></li>
		</ul>
		<div style="text-align: right;"><a href="/allrank/1">all time ranking &gt;&gt;</a></div>
	</nav>
	<div style="width:300px; height: 250px;">
		<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
		<!-- 300x250, IT Penguin -->
		<ins class="adsbygoogle"
		     style="display:inline-block;width:300px;height:250px"
		     data-ad-client="ca-pub-2855357403949640"
		     data-ad-slot="9162065787"></ins>
		<script>
		(adsbygoogle = window.adsbygoogle || []).push({});
		</script>
	</div>
	<nav>
		<h1><a href="http://www.it-penguin.com/">IT Penguin sites</a></h1>
		<a href="http://travel.it-penguin.com/" style="display: block; margin-left: -20px;"><img src="https://lh5.googleusercontent.com/-9PFBpki_OaQ/T5uCxzliTQI/AAAAAAAAEjk/uDrNwW9Ifz0/s800/travel.png" height="80" width="300" alt="旅ペンギン"/></a>
		筆者の旅日記<br/><br/>
		<a href="http://alpen.it-penguin.com/" style="display: block; margin-left: -20px;"><img src="https://lh3.googleusercontent.com/-qVR1sBxSDB0/T5uCZshRhBI/AAAAAAAAEjM/ZNcVGNmjyu4/s800/alpen.png" height="80" width="300" alt="世界アルペン遺産"/></a>
		日本各地に発掘される三角屋根の遺跡の謎に迫る
		<ul>
			<li><a href="http://election.it-penguin.com/">国政選挙 議席予想・速報 まとめ</a><div>国政選挙 選挙特番観察記</div></li>
			<li><a href="https://plus.google.com/u/0/117563385764336437850?rel=author">Google+</a><div>プロフィール</div></li>
		</ul>
	</nav>
	<nav>
		<h1>Rating</h1>
		<ul>
			<li><a href="/rating/10/1"><span class="star"><span class="star10"></span></span>&nbsp;[91~100点]</a> (${countByRate[0]})</li>
			<li><a href="/rating/9/1"><span class="star"><span class="star9"></span></span>&nbsp;[81~90点]</a> (${countByRate[1]})</li>
			<li><a href="/rating/8/1"><span class="star"><span class="star8"></span></span>&nbsp;[71~80点]</a> (${countByRate[2]})</li>
			<li><a href="/rating/7/1"><span class="star"><span class="star7"></span></span>&nbsp;[61~70点]</a> (${countByRate[3]})</li>
			<li><a href="/rating/6/1"><span class="star"><span class="star6"></span></span>&nbsp;[51~60点]</a> (${countByRate[4]})</li>
			<li><a href="/rating/5/1"><span class="star"><span class="star5"></span></span>&nbsp;[41~50点]</a> (${countByRate[5]})</li>
			<li><a href="/rating/4/1"><span class="star"><span class="star4"></span></span>&nbsp;[31~40点]</a> (${countByRate[6]})</li>
			<li><a href="/rating/3/1"><span class="star"><span class="star3"></span></span>&nbsp;[21~30点]</a> (${countByRate[7]})</li>
			<li><a href="/rating/2/1"><span class="star"><span class="star2"></span></span>&nbsp;[11~20点]</a> (${countByRate[8]})</li>
			<li><a href="/rating/1/1"><span class="star"><span class="star1"></span></span>&nbsp;[1~10点]</a> (${countByRate[9]})</li>
			<li><a href="/rating/0/1"><span class="star"><span class="star0"></span></span>&nbsp;[0点]</a> (${countByRate[10]})</li>
		</ul>
	</nav>
	<nav>
		<h1>Archives</h1>
		<ul class="tree">
			<c:forEach items="${arcCounter}" var="countByMonth" varStatus="yearStatus">
				<li>
					<c:if test="${yearStatus.index == 0}">
						<span class="open"></span>
					</c:if>
					<c:if test="${yearStatus.index != 0}">
						<span class="close"></span>
					</c:if>
					<a href="/archives/${countByMonth.key}/1">${countByMonth.key}年</a> (${countByYear[countByMonth.key]})
					<ul style="${monthStyle}">
						<c:forEach items="${countByMonth.value}" var="month">
							<li><span class="close"></span><a href="/archives/${countByMonth.key}/${month.key}/1">${month.key}月</a> (${month.value})
							</li>
						</c:forEach>
					</ul>
					<c:set value="display:none;" var="monthStyle" />
				</li>
			</c:forEach>
		</ul>
	</nav>

<script type="text/javascript">
$(function(){
	$("ul.tree li").each(function(){
		var li = $(this);
		var img = li.children("span");
		var isOpen = img.hasClass("open");
		var ul = li.children("ul");
		var isLoaded = ul.length != 0;
		if (! isLoaded) {
			var href = $(this).children("a").attr("href");
			href = href.replace("archives","archiveList");
			href = href.substring(0, href.length - 2);
		}
		img.click(function(){
			if (isOpen) {
				$(this).removeClass('open');
				$(this).addClass('close');
				ul.hide();
				isOpen = false;
			} else {
				$(this).removeClass('close');
				$(this).addClass('open');
				if (!isLoaded) {
					$.getJSON(href, function(json){
						ul = $("<ul/>");
						li.append(ul);
						for(var i = 0; i < json.length; i++) {
							ul.append('<li><a href="/review/' + json[i].itemId +'">' + json[i].title + "</a></li>");
						}
						isLoaded = true;
					});
				}
				ul.show();
				isOpen = true;
			}
		})
	});
});
</script>
</c:if>
<c:if test="${isMobile}">
	<nav>
		<h1>Rating</h1>
		<ul>
			<li><a href="/rating/5/1"><span class="star1" style="position: static;"></span>×5</a></li>
			<li><a href="/rating/4/1"><span class="star1" style="position: static;"></span>×4</a></li>
			<li><a href="/rating/3/1"><span class="star1" style="position: static;"></span>×3</a></li>
			<li><a href="/rating/2/1"><span class="star1" style="position: static;"></span>×2</a></li>
			<li><a href="/rating/1/1"><span class="star1" style="position: static;"></span>×1</a></li>
		</ul>
		<a href="/search" style="position:absolute; right:0;"><img alt="" src="/img/search.png" style="vertical-align: bottom;"/>検索</a>
	</nav>
	<nav>
		<h1>Archives</h1>
		<ul>
			<c:forEach items="${arcCounter}" var="countByMonth">
				<li><a href="/archives/${countByMonth.key}/1">${countByMonth.key}</a>
				<ul>
					<c:forEach items="${countByMonth.value}" var="month">
						<li><a href="/archives/${countByMonth.key}/${month.key}/1">${month.key}</a>
						</li>
					</c:forEach>
				</ul>
				</li>
			</c:forEach>
		</ul>
	</nav>
	<nav>
		<h1><a href="http://www.it-penguin.com/">IT Penguin sites</a></h1>
		<ul>
			<li><a href="http://travel.it-penguin.com/">旅ペンギン</a><div>筆者の旅日記</div></li>
			<li><a href="http://alpen.it-penguin.com/">アルペン遺産</a><div>日本各地に散見する三角屋根の謎に迫る</div></li>
		</ul>
	</nav>
</c:if>

<c:if test="${!isMobile}">
	<nav>
		<h1>Subscribe</h1>
		<a href="/feed"><img alt="" src="/img/feed.png"/> ATOM</a>
	</nav>
<aside style="margin:1em; font-size:80%;">本サイト上で表示されるコンテンツの一部は、アマゾンジャパン株式会社またはその関連会社により提供されたものです。<br/>
かかるコンテンツは、お客様に「現状有姿」で提供されており、随時変更または削除される場合があります。</aside>
	<div style="text-align:center;padding-bottom:1em;">
		<img src="http://code.google.com/appengine/images/appengine-silver-120x30.gif" 
		alt="Powered by Google App Engine"/>
	</div>
</c:if>
